package com.jwsoft.manager.core.integration.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.data.core.util.PagerUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.EnrollPreTypeEnum;
import com.jwsoft.manager.common.enums.SaveTypeEnum;
import com.jwsoft.manager.common.vo.eduBusiEnrollOrder.EduBusiEnrollOrderQueryVO;
import com.jwsoft.manager.common.vo.eduHousehold.EduHouseholdVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollPre.EduStudentEnrollPreVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.EduHouseholdService;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollPreService;
import com.jwsoft.manager.core.integration.EduBusiEnrollOrderIntegration;
import com.jwsoft.manager.core.integration.EduHouseholdIntegration;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;
import java.util.List;
import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.common.vo.eduHouseholdOffline.EduHouseholdOfflineVO;
import com.jwsoft.manager.common.vo.eduHouseholdOffline.EduHouseholdOfflineKeyVO;
import com.jwsoft.manager.common.vo.eduHouseholdOffline.EduHouseholdOfflineQueryVO;
import com.jwsoft.manager.core.integration.EduHouseholdOfflineIntegration;
import com.jwsoft.manager.core.dao.service.EduHouseholdOfflineService;

/**
 * 线下户籍新增业务实现类
 *
 * @author wangt
 * @since 2024-06-06
 */
@ApiService(funcCode = "eduHouseHoldOffline", title = "线下户籍新增")
public class EduHouseholdOfflineIntegrationImpl implements EduHouseholdOfflineIntegration {

    @Autowired
    public EduHouseholdOfflineService eduHouseholdOfflineService;

    @Autowired
    private EduHouseholdService eduHouseholdService;

    @Autowired
    private EduBusiEnrollOrderIntegration eduBusiEnrollOrderIntegration;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private EduHouseholdIntegration eduHouseholdIntegration;

    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;

    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;

    @Override
    @OpApi(funcCode = "eduHouseHoldOffline0001", title = "线下户籍新增分页查询", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduHouseholdOfflineVO> getList(EduHouseholdOfflineQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduHouseholdOffline> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StringUtils.isNotBlank(vo.getAuthStatus()),EduHouseholdOffline::getAuthStatus,vo.getAuthStatus())
                .eq(StringUtils.isNotBlank(vo.getIdcard()), EduHouseholdOffline::getIdcard,vo.getIdcard());
        List<EduHouseholdOffline> list = eduHouseholdOfflineService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduHouseholdOffline> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduHouseholdOfflineVO> resultList = Convert.toList(EduHouseholdOfflineVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduHouseHoldOffline0002", title = "线下户籍新增根据主键查询详情", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public EduHouseholdOfflineVO getById(EduHouseholdOfflineKeyVO vo) {
        EduHouseholdOffline entity = eduHouseholdOfflineService.getById(vo.getHouseholdId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduHouseholdOfflineVO result = Convert.convert(EduHouseholdOfflineVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduHouseHoldOffline0003", title = "线下户籍新增保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduHouseholdOfflineVO vo) {
        //主键为空为新增校验
        if(StringUtils.isBlank(vo.getIdcard())){
            throw new AppException("学生身份证不能为空");
        }
        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduHouseHoldOffline0004", title = "线下户籍新增新增", funcType = FuncTypeEnum.insert,publicFlag = BoolEnum.TRUE)
    @SaveOplog(
            operationType = "eduHouseHoldOffline0004",
            operationName = "线下户籍新增新增",
            dataType = "householdId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduHouseholdOfflineVO add(EduHouseholdOfflineVO vo) {
        Integer year = eduHelper.thisYear();
        vo.setYear(year);
        //保存前校验
        checkSave(vo);

        QueryWrapper<EduHousehold> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduHousehold::getIdcard,vo.getIdcard());
        List<EduHousehold> enrollPreList = eduHouseholdService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(enrollPreList)){
            throw new AppException(vo.getIdcard()+"该身份证已办理户籍登记！");
        }

        QueryWrapper<EduHouseholdOffline> queryWrapperOffline = new QueryWrapper<>();
        queryWrapperOffline.lambda().eq(EduHouseholdOffline::getIdcard,vo.getIdcard());
        List<EduHouseholdOffline> enrollPreOfflineList = eduHouseholdOfflineService.list(queryWrapperOffline);
        if(!CollectionUtils.isEmpty(enrollPreOfflineList)){
            throw new AppException(vo.getIdcard()+"该身份证已办理线下户籍登记，请不要重复登记！");
        }


        vo.setAuthStatus(AuthStatusEnum.NODO.getType());

        //保存数据
        EduHouseholdOffline entity = Convert.convert(EduHouseholdOffline.class, vo);
        eduHouseholdOfflineService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setHouseholdId(entity.getHouseholdId());


        EduBusiEnrollOrderQueryVO orderQueryVO = new EduBusiEnrollOrderQueryVO();
        orderQueryVO = Convert.convert(EduBusiEnrollOrderQueryVO.class, vo);
        String orderNum = eduBusiEnrollOrderIntegration.appDistributeOrderNum(orderQueryVO);
        vo.setOrderNum(orderNum);


        return vo;
    }

    @Override
    @OpApi(funcCode = "eduHouseHoldOffline0005", title = "线下户籍新增修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduHouseHoldOffline0005",
            operationName = "线下户籍新增修改",
            dataType = "householdId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduHouseholdOfflineVO edit(EduHouseholdOfflineVO vo) {
        if (ObjectUtils.isEmpty(vo.getHouseholdId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduHouseholdOffline oldEntity = eduHouseholdOfflineService.getById(vo.getHouseholdId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduHouseholdOffline entity = Convert.convert(EduHouseholdOffline.class, vo);
        eduHouseholdOfflineService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduHouseHoldOffline0006", title = "线下户籍新增根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduHouseHoldOffline0006",
            operationName = "线下户籍新增删除",
            dataType = "householdId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduHouseholdOfflineKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getHouseholdId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduHouseholdOffline entity = eduHouseholdOfflineService.getById(vo.getHouseholdId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduHouseholdOfflineService.removeById(vo.getHouseholdId());
    }

    @Override
    @OpApi(funcCode = "eduHouseHoldOffline0010", title = "线下户籍登记保存", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduHouseHoldOffline0010",
            operationName = "线下户籍登记保存",
            dataType = "householdId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduHouseholdVO saveOffline(EduHouseholdOfflineVO vo) {
        if (ObjectUtils.isEmpty(vo.getHouseholdId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduHouseholdOffline oldEntity = eduHouseholdOfflineService.getById(vo.getHouseholdId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }


        //保存数据
        oldEntity.setAuthStatus(vo.getAuthStatus());
        eduHouseholdOfflineService.updateById(oldEntity);


        if(AuthStatusEnum.YES.getType().equals(vo.getAuthStatus())){
            EduHouseholdVO houseHoldVO = Convert.convert(EduHouseholdVO.class,oldEntity);
            eduHouseholdIntegration.add(houseHoldVO);
            clearCache(houseHoldVO.getIdcard());
            return houseHoldVO;
        }else {
            return null;
        }
    }
    //清除缓存
    private void clearCache(String idcard) {
        //查询人员
        if (StringUtils.isBlank(idcard)) {
            return;
        }

        QueryWrapper<EduStudentEnrollPre> queryPreWrapper = new QueryWrapper<>();
        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId, EduStudentEnrollPre::getIdcard, EduStudentEnrollPre::getFatherIdcard, EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear, eduHelper.thisYear())
                .and(wrapper -> {
                    wrapper.eq(EduStudentEnrollPre::getIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                });
        List<EduStudentEnrollPre> list = eduStudentEnrollPreService.list(queryPreWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (EduStudentEnrollPre pre : list) {
            //户籍
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }
    }



}
